'use client';

import React, { useRef, useState, useEffect } from 'react';
import { ProTable, ProColumns, ActionType } from '@ant-design/pro-components';
import { Button, Space, Card, Row, Col, Select, DatePicker, Input, Modal, Cascader } from 'antd';
import { PlusOutlined, EditOutlined, EyeOutlined, CalendarOutlined, TeamOutlined, ReloadOutlined } from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
import { useRouter } from 'next/navigation';
import { useMessage } from '../../hooks/useMessage';
import { INSTRUMENT_STATUS_MAP, INSTRUMENT_STATUS_OPTIONS } from '@/constants/instrument';
import { instrumentApi } from '@/apis/instrument';
import { categoryApi } from '@/apis/category';
import { getUserList } from '@/apis/user';
import { InstrumentListItem, InstrumentStatus, InstrumentQueryParams, CategoryResponse } from '@/types/instrument';

// 用户选项接口
interface UserOption {
  label: string;
  value: number;
}

// 查找分类路径的辅助函数
function findCategoryPath(categories: CategoryResponse[], id: number): number[] {
  for (const cat of categories) {
    if (cat.id === id) return [cat.id];
    if (cat.children) {
      for (const sub of cat.children) {
        if (sub.id === id) return [cat.id, sub.id];
      }
    }
  }
  return [];
}

const InstrumentsPage: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const message = useMessage();
  const [searchParams, setSearchParams] = useState({
    name: '',
    categoryId: undefined as number | undefined,
    status: '' as InstrumentStatus | '',
    curatorUserId: undefined as number | undefined,
    startDate: null as Dayjs | null,
    endDate: null as Dayjs | null,
  });
  const router = useRouter();

  // 分类和用户数据
  const [categories, setCategories] = useState<CategoryResponse[]>([]);
  const [userOptions, setUserOptions] = useState<UserOption[]>([]);
  const [loading, setLoading] = useState(false);

  // 加载分类和用户数据
  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    setLoading(true);
    try {
      // 并行加载分类和用户数据
      const [categoryTree, users] = await Promise.all([
        categoryApi.getCategoryTree(),
        getUserList()
      ]);

      setCategories(categoryTree);

      const userOpts: UserOption[] = users.map(user => ({
        label: `${user.name}(${user.phoneNumber})`,
        value: user.id,
      }));
      setUserOptions(userOpts);
    } catch (error) {
      console.error('加载初始数据失败:', error);
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({
      name: '',
      categoryId: undefined,
      status: '',
      curatorUserId: undefined,
      startDate: null,
      endDate: null,
    });
    actionRef.current?.reload();
  };

  // 查询
  const handleSearch = () => {
    actionRef.current?.reload();
  };

  // 修改状态
  const handleStatusChange = (record: InstrumentListItem, newStatus: InstrumentStatus) => {
    Modal.confirm({
      title: '确认修改状态',
      content: `确定要将仪器状态修改为 ${INSTRUMENT_STATUS_MAP[newStatus]} 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await instrumentApi.updateInstrumentStatus({
            id: record.id,
            status: parseInt(String(newStatus))
          });
          message.success('状态修改成功');
          actionRef.current?.reload();
        } catch {
          message.error('状态修改失败');
        }
      },
    });
  };

  // 处理编辑按钮点击
  const handleEdit = (record: InstrumentListItem) => {
    if (record.status === InstrumentStatus.ONLINE) {
      Modal.confirm({
        title: '提示',
        content: '仪器状态需在维护中、已下线状态下修改，请先调整仪器状态',
        okText: '确定',
        cancelText: '取消',
      });
      return;
    }
    router.push(`/instruments/info?mode=edit&id=${record.id}`);
  };

  // 跳转到排期页面
  const handleSchedule = (record: InstrumentListItem) => {
    router.push(`/instruments/info?id=${record.id}&defaultTab=schedule`);
  };

  // 跳转到培训名单页面
  const handleTrainingList = (record: InstrumentListItem) => {
    router.push(`/instruments/training-list?id=${record.id}`);
  };

  // 表格列定义
  const columns: ProColumns<InstrumentListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      fixed: 'left',
      render: (_, __, index) => index + 1,
    },
    {
      title: '仪器名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 150,
    },
    {
      title: '负责人',
      dataIndex: 'curatorNames',
      key: 'curatorNames',
      width: 150,
      render: (_, record: InstrumentListItem) => record?.curatorNames?.join(', '),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      sorter: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (_, record) => {
        return (
          <Select
            value={record.status}
            size="small"
            style={{ width: 100 }}
            onChange={(value) => handleStatusChange(record, value)}
            options={INSTRUMENT_STATUS_OPTIONS.map(option => ({
              label: option.label,
              value: option.value,
            }))}
          />
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            style={{ color: '#69cac3' }}
            icon={<EyeOutlined />}
            onClick={() => router.push(`/instruments/info?id=${record.id}&mode=view`)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: '#69cac3' }}
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: '#69cac3' }}
            icon={<CalendarOutlined />}
            onClick={() => handleSchedule(record)}
          >
            排期
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: '#69cac3' }}
            icon={<TeamOutlined />}
            onClick={() => handleTrainingList(record)}
          >
            自主上机培训名单
          </Button>
        </Space>
      ),
    },
  ];

  // API数据请求
  const request = async (params: { current?: number; pageSize?: number; [key: string]: unknown }) => {
    try {
      const queryParams: InstrumentQueryParams = {
        current: params.current,
        size: params.pageSize,
        name: searchParams.name || undefined,
        searchKey: searchParams.name || undefined,
        categoryId: searchParams.categoryId || undefined,
        curatorUserId: searchParams.curatorUserId || undefined,
        status: searchParams.status || undefined,
        startDate: searchParams.startDate?.format('YYYY-MM-DD') || undefined,
        endDate: searchParams.endDate?.format('YYYY-MM-DD') || undefined,
      };

      const response = await instrumentApi.getInstrumentPage(queryParams);

      return {
        data: response.records,
        success: true,
        total: response.total,
      };
    } catch (error) {
      console.error('获取仪器列表失败:', error);
      message.error('获取仪器列表失败');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', fontSize: '20px', fontWeight: 'bold' }}>
        仪器管理
      </div>
      
      {/* 搜索表单 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <div style={{ marginBottom: '8px' }}>仪器名称</div>
            <Input
              placeholder="请输入仪器名称"
              value={searchParams.name}
              onChange={(e) => setSearchParams({ ...searchParams, name: e.target.value })}
            />
          </Col>
          <Col span={6}>
            <div style={{ marginBottom: '8px' }}>分类名称</div>
            <Cascader
              placeholder="请选择分类"
              style={{ width: '100%' }}
              options={categories.map(cat => ({
                value: cat.id,
                label: cat.name,
                children: (cat.children || []).map(sub => ({
                  value: sub.id,
                  label: sub.name,
                })),
              }))}
              value={searchParams.categoryId ? findCategoryPath(categories, searchParams.categoryId) : undefined}
              onChange={(value) => {
                const categoryId = value && value.length > 0 ? value[value.length - 1] as number : undefined;
                setSearchParams({ ...searchParams, categoryId });
              }}
              changeOnSelect
              allowClear
              showSearch
            />
          </Col>
          <Col span={6}>
            <div style={{ marginBottom: '8px' }}>状态</div>
            <Select
              placeholder="全部"
              style={{ width: '100%' }}
              value={searchParams.status || undefined}
              onChange={(value) => setSearchParams({ ...searchParams, status: value || '' })}
              allowClear
            >
              <Select.Option value="">全部</Select.Option>
              {INSTRUMENT_STATUS_OPTIONS.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            <div style={{ marginBottom: '8px' }}>负责人</div>
            <Select
              placeholder="全部"
              style={{ width: '100%' }}
              value={searchParams.curatorUserId || undefined}
              onChange={(value) => setSearchParams({ ...searchParams, curatorUserId: value })}
              allowClear
              showSearch
              filterOption={(input, option) =>
                String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
            >
              {userOptions.map(option => (
                <Select.Option key={option.value} value={option.value} label={option.label}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Col>
        </Row>
        
        <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
          <Col span={6}>
            <div style={{ marginBottom: '8px' }}>创建时间</div>
            <DatePicker.RangePicker
              style={{ width: '100%' }}
              value={searchParams.startDate && searchParams.endDate ? [searchParams.startDate, searchParams.endDate] : null}
              onChange={(dates) => {
                setSearchParams({ 
                  ...searchParams, 
                  startDate: dates?.[0] || null,
                  endDate: dates?.[1] || null
                });
              }}
              placeholder={['开始日期', '结束日期']}
            />
          </Col>
          <Col span={18} style={{ display: 'flex', alignItems: 'end', gap: '8px' }}>
            <Button type="primary" onClick={handleSearch} style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}>
              查询
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleReset}>
              重置
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => router.push('/instruments/info?mode=create')}
              style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
            >
              新增
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 数据表格 */}
      <ProTable<InstrumentListItem>
        actionRef={actionRef}
        rowKey="id"
        search={false}
        request={request}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => 
            `共 ${total} 条`,
        }}
        scroll={{ x: 1200 }}
        options={{
          reload: true,
          density: false,
          setting: false,
        }}
        toolBarRender={false}
      />
    </div>
  );
};

export default InstrumentsPage; 